<template>
  <div class="user-profile">
    <el-card class="profile-card">
      <template #header>
        <div class="card-header">
          <h2>个人资料</h2>
        </div>
      </template>
      
      <el-form 
        ref="profileFormRef"
        :model="profileForm"
        :rules="profileRules"
        label-width="100px"
        class="profile-form"
        v-loading="loading"
      >
        <div class="avatar-container">
          <el-avatar :size="100" :src="avatarUrl">
            <el-icon><User /></el-icon>
          </el-avatar>
          <el-upload
            class="avatar-uploader"
            action="/api/file/upload"
            :headers="uploadHeaders"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <el-button type="primary" size="small">更换头像</el-button>
          </el-upload>
        </div>
        
        <el-form-item label="用户名">
          <el-input v-model="profileForm.username" disabled />
        </el-form-item>
        
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="profileForm.nickname" placeholder="请输入昵称" />
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="profileForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="profileForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="profileForm.gender">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
            <el-radio :label="0">保密</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="生日" prop="birthday">
          <el-date-picker
            v-model="profileForm.birthday"
            type="date"
            placeholder="选择生日"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        
        <el-form-item label="常驻城市" prop="location">
          <el-input v-model="profileForm.location" placeholder="请输入常驻城市" />
        </el-form-item>
        
        <el-form-item label="个人简介" prop="bio">
          <el-input
            v-model="profileForm.bio"
            type="textarea"
            :rows="4"
            placeholder="介绍一下自己吧"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="submitting">保存修改</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { User } from '@element-plus/icons-vue';
import { useUserStore } from '@/stores/user';

const userStore = useUserStore();
const loading = ref(false);
const submitting = ref(false);
const profileFormRef = ref(null);

// 表单数据
const profileForm = reactive({
  username: '',
  nickname: '',
  email: '',
  phone: '',
  avatar: '',
  gender: 0,
  birthday: '',
  location: '',
  bio: ''
});

// 头像URL
const avatarUrl = computed(() => {
  if (profileForm.avatar) {
    // 如果头像是完整URL则直接使用，否则拼接API基础URL
    if (profileForm.avatar.startsWith('http')) {
      return profileForm.avatar;
    } else {
      return `${import.meta.env.VITE_API_BASE_URL}/file/avatar/${profileForm.avatar}`;
    }
  }
  return '';
});

// 上传头像的请求头
const uploadHeaders = computed(() => {
  return {
    Authorization: `Bearer ${localStorage.getItem('token')}`
  };
});

// 表单验证规则
const profileRules = {
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  bio: [
    { max: 500, message: '个人简介不能超过500个字符', trigger: 'blur' }
  ]
};

// 获取用户信息
const fetchUserProfile = async () => {
  loading.value = true;
  try {
    // 从用户存储中获取当前用户信息
    const user = userStore.user;
    if (user) {
      profileForm.username = user.username || '';
      profileForm.nickname = user.nickname || '';
      profileForm.email = user.email || '';
      profileForm.phone = user.phone || '';
      profileForm.avatar = user.avatar || '';
      profileForm.gender = user.gender || 0;
      profileForm.birthday = user.birthday || '';
      profileForm.location = user.location || '';
      profileForm.bio = user.bio || '';
    }
  } catch (error) {
    console.error('获取用户信息失败:', error);
    ElMessage.error('获取用户信息失败');
  } finally {
    loading.value = false;
  }
};

// 头像上传成功回调
const handleAvatarSuccess = (response, uploadFile) => {
  if (response.code === 200) {
    profileForm.avatar = response.data.url;
    ElMessage.success('头像上传成功');
  } else {
    ElMessage.error(response.message || '头像上传失败');
  }
};

// 头像上传前的验证
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg';
  const isPNG = file.type === 'image/png';
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG && !isPNG) {
    ElMessage.error('头像只能是JPG或PNG格式!');
    return false;
  }
  if (!isLt2M) {
    ElMessage.error('头像大小不能超过2MB!');
    return false;
  }
  return true;
};

// 提交表单
const submitForm = async () => {
  profileFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true;
      try {
        // 准备提交的数据
        const updateData = {
          email: profileForm.email,
          phone: profileForm.phone,
          avatar: profileForm.avatar,
          gender: profileForm.gender,
          nickname: profileForm.nickname,
          birthday: profileForm.birthday,
          location: profileForm.location,
          bio: profileForm.bio
        };
        
        // 调用用户存储中的更新方法
        await userStore.updateUserProfile(updateData);
        ElMessage.success('个人资料更新成功');
      } catch (error) {
        console.error('更新个人资料失败:', error);
        ElMessage.error(error.message || '更新个人资料失败');
      } finally {
        submitting.value = false;
      }
    }
  });
};

// 重置表单
const resetForm = () => {
  fetchUserProfile();
};

onMounted(() => {
  fetchUserProfile();
});
</script>

<style scoped>
.user-profile {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.profile-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.avatar-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 20px;
}

.avatar-uploader {
  margin-top: 10px;
}

.profile-form {
  max-width: 600px;
}

@media (max-width: 768px) {
  .user-profile {
    padding: 10px;
  }
}
</style> 